<template>
  <div class="degree-order es-each-line">
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
      <div class="widget am-cf">
        <div class="widget-body am-fr">
          <div class="am-u-md-12 one-line">
            <el-select
              size="small"
              class="am-u-sm-12 am-u-md-12 am-u-lg-3"
              v-model="query.areaTeamId"
              placeholder="请选择区域"
            >
              <el-option
                v-for="item in areaTeams"
                :key="item.areaTeamId"
                :label="item.name"
                :value="item.areaTeamId"
              >
              </el-option>
            </el-select>

            <el-select
              size="small"
              class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
              v-model="query.periodId"
              placeholder="请选择期数"
              clearable
            >
              <el-option
                v-for="item in periods"
                :key="item.periodId"
                :label="item.periodName"
                :value="item.periodId"
              >
              </el-option>
            </el-select>
            <el-select
              clearable
              class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
              v-model="query.productId"
              placeholder="产品"
              style="float:left"
            >
              <el-option
                v-for="item in products"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select
              clearable
              class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
              v-model="query.status"
              placeholder="状态"
            >
              <el-option
                label="启用"
                :value="1"
              >
              </el-option>
              <el-option
                label="禁用"
                :value="0"
              >
              </el-option>
            </el-select>

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group am-u-end">
              <button
                @click="search"
                type="button"
                class="btn-search am-btn am-btn-default am-btn-success"
              >
                <span class="am-icon-search"></span>查询
              </button>
              <button
                @click="showDialog('add')"
                type="button"
                class="btn-search am-btn am-btn-default am-btn-success"
              >
                + 新增
              </button>
            </div>
          </div>

        </div>

        <div class="am-u-sm-12">
          <el-table
            :data="tableData"
            border
            stripe
            :empty-text="tableNoDataTips"
            style="min-width: 100%"
          >
            <el-table-column
              prop="areaTeamName"
              label="区域"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              label="期数"
              prop="periodName"
              min-width="130"
            >
            </el-table-column>
            <el-table-column
              label="适用产品"
              prop="productNames"
              min-width="180"
            >
              <template scope="scope">
                <div>
                  <el-popover
                    ref="popover"
                    placement="right"
                    width="400"
                    trigger="hover"
                  >
                    {{ scope.row.productNames}}
                  </el-popover>
                  <div
                    class="showProductNames"
                    v-popover:popover
                  >
                    {{ scope.row.productNames}}
                  </div>
                </div>

              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="收费段次"
              prop="chargeSegment"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="收费开始讲次"
              prop="startLectureNo"
              min-width="180"
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="收费结束讲次"
              prop="endLectureNo"
              min-width="180"
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="收费开始日期"
              prop="startChargeTime"
              min-width="200"
            >
              <template scope="scope">
                {{ scope.row.startChargeTime | formatTime}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="状态"
              min-width="100"
            >
              <template scope="scope">
                {{scope.row.status == 1 ? '启用' : '禁用' }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="最后操作人"
              prop="operatorName"
              min-width="180"
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="最后操作时间"
              prop="updateTime"
              min-width="200"
            >
              <template scope="scope">
                {{ scope.row.updateTime | formatTime}}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              min-width="100"
            >
              <template scope="scope">
                <el-button @click="showDialog('edit', scope.row)">
                  编辑
                </el-button>
              </template>

            </el-table-column>
          </el-table>
        </div>

        <div class="am-u-lg-12 am-cf">
          <div class="am-fr">
            <pagination
              v-bind:total="total"
              v-bind:pageNo="query.pageNo"
              v-bind:pageSize="query.pageSize"
              @paging="handleSearch"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="dialogTxt"
      :visible="dialogVisible"
      size="small"
      :before-close="dialogClose"
      :key="dialogVisible"
    >
      <el-form
        :model="editForm"
        ref="form"
      >
        <el-form-item
          label="适用区域"
          prop="areaTeamId"
          label-width="130px"
          :rules="[{ required: true, message: '适用区域不能为空'}]"
        >
          <el-select
            size="small"
            v-model="editForm.areaTeamId"
            placeholder="请选择区域"
            @change="areaTeamChange"
          >
            <el-option
              v-for="item in areaTeams"
              :key="item.areaTeamId"
              :label="item.name"
              :value="item.areaTeamId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="适用期数"
          label-width="130px"
          prop="periodId"
          :rules="[{ required: true, message: '适用期数不能为空'}]"
        >
          <el-select
            size="small"
            v-model="editForm.periodId"
            placeholder="请选择期数"
            clearable
          >
            <el-option
              v-for="item in editPeriods"
              :key="item.periodId"
              :label="item.periodName"
              :value="item.periodId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="适用产品"
          label-width="130px"
          prop="productIds"
        >
          <el-select
            v-model="editForm.productIds"
            multiple
            filterable
            allow-create
            class="productSelect"
            placeholder="请选择产品"
          >
            <el-option
              v-for="item in editProducts"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="状态"
          label-width="130px"
          prop="status"
          :rules="[{ required: true, message: '状态不能为空'}]"
        >
          <el-select
            clearable
            size="small"
            v-model="editForm.status"
            placeholder="状态"
          >
            <el-option
              label="启用"
              value="1"
            >
            </el-option>
            <el-option
              label="禁用"
              value="0"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="收费段次"
          label-width="130px"
          prop="chargeSegment"
          :rules="[{ required: true, message: '收费段次不能为空'},
           { validator: numberValidate, trigger: 'change'},]"
        >
          <el-input
            class="chargeSegment"
            placeholder="收费段次"
            v-model="editForm.chargeSegment"
          ></el-input>
        </el-form-item>
        <div style="overflow:hidden">
          <el-form-item
            label="收费讲次"
            label-width="130px"
            prop="startLectureNo"
            class="lectureNoItem"
            :rules="[{ required: true, message: '开始讲次不能为空'},
            { validator: numberValidate, trigger: 'change'},
            { validator: validateStartLectureNo, trigger: 'change'}]"
          >
            <el-input
              class="lectureNoInput"
              v-model="editForm.startLectureNo"
            ></el-input>
          </el-form-item>
          <div class="lectureNoTxt">至</div>
          <el-form-item
            prop="endLectureNo"
            class="lectureNoItem"
            :rules="[{ required: true, message: '结束讲次不能为空'},
            { validator: numberValidate, trigger: 'change'},
            { validator: validateEndLectureNo, trigger: 'change'}]"
          >
            <el-input
              class="lectureNoInput"
              v-model="editForm.endLectureNo"
            ></el-input>
          </el-form-item>
        </div>

        <el-form-item
          label="收费开始时间"
          label-width="130px"
          prop="startChargeTime"
          style="clear:both"
          :rules="[{ required: true, message: '收费开始时间不能为空'}]"
        >
          <el-date-picker
            :editable='false'
            v-model="editForm.startChargeTime"
            type="datetime"
            placeholder="选择日期时间"
            align="right"
            class="startChargeTime"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogClose">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import io from "../../lib/io";
import moment from "moment";
import Pagination from "../base/Pagination";
export default {
  data() {
    return {
      trace: [
        {
          value: "1",
          name: "是"
        },
        {
          value: "0",
          name: "否"
        }
      ],
      tableNoDataTips: "暂无数据",
      tableData: [],
      segmentNos: [
        {
          value: "1",
          name: "段次1"
        },
        {
          value: "2",
          name: "段次2"
        },
        {
          value: "3",
          name: "段次3"
        },
        {
          value: "4",
          name: "段次4"
        },
        {
          value: "5",
          name: "段次5"
        },
        {
          value: "6",
          name: "段次6"
        },
        {
          value: "7",
          name: "段次7"
        },
        {
          value: "8",
          name: "段次8"
        }
      ],
      classDate: "",
      query: {
        areaTeamId:
          (window.config.areaTeams[0] &&
            window.config.areaTeams[0].areaTeamId) ||
          "",
        periodId: "",
        pageNo: 1,
        pageSize: 10,
        productId: "",
        status: ""
      },
      editForm: {
        areaTeamId: "",
        periodId: "",
        productIds: [],
        status: "",
        startChargeTime: ""
      },
      total: 0,
      periods: [],
      products: [],
      editProducts: [],
      editPeriods: [],
      dialogVisible: false,
      dialogTxt: ""
    };
  },
  components: {
    Pagination
  },
  watch: {
    classDate(newVal) {
      this.query.startDate = newVal[0]
        ? this.$options.filters.formatDate(newVal[0])
        : "";
      this.query.endDate = newVal[1]
        ? this.$options.filters.formatDate(newVal[1])
        : "";
    },
    "query.areaTeamId": function() {
      this.query.productId = "";
      this.query.periodId = "";
      this.loadProductData();
      this.loadPeriodData();
    }
  },
  methods: {
    numberValidate(rule, value, callback) {
      let reg = /^[0-9]*$/;
      if (value) {
        if (reg.test(value)) {
          callback();
        } else {
          callback("请输入数字");
        }
      }
    },
    validateStartLectureNo(rule, value, callback) {
      if (this.editForm.endLectureNo) {
        let currentValue = value ? Number(value): 0
        if (currentValue <= this.editForm.endLectureNo) {
          callback();
        } else {
          callback("不能大于结束讲次");
        }
      } else {
        callback();
      }
    },
    validateEndLectureNo(rule, value, callback) {
      if (this.editForm.startLectureNo) {
          let currentValue = value ? Number(value): 0
        if (currentValue >= this.editForm.startLectureNo) {
          callback();
        } else {
          callback("不能小于开始讲次");
        }
      } else {
        callback();
      }
    },
    areaTeamChange() {
      this.editForm.productIds = [];
      this.editForm.periodId = "";
      this.getEditProducts();
      this.loadEditPeriodData();
    },
    submitForm() {
      this.$refs.form.validate(res => {
        if (res) {
          this.addDialogData();
        }
      });
    },
    dialogClose() {
      this.dialogVisible = false;
      this.editProducts = [];
      this.editPeriods = [];
      this.editForm = {
        areaTeamId: "",
        periodId: "",
        productIds: [],
        status: "",
        startChargeTime: ""
      };
    },
    showDialog(type, rowData) {
      if (type === "add") {
        this.dialogTxt = "新增";
      } else {
        this.dialogTxt = "编辑";
        let {
          chargeSettingId,
          areaTeamId,
          status,
          startChargeTime,
          endLectureNo,
          chargeSegment,
          startLectureNo,
          periodId,
          productIds
        } = rowData;
        let tempProductIds;
        if (productIds) {
          tempProductIds = productIds.split(",");
        }
        this.editForm = {
          chargeSettingId,
          areaTeamId,
          status,
          startChargeTime: startChargeTime
            ? new Date(Number(startChargeTime))
            : undefined,
          endLectureNo,
          chargeSegment,
          startLectureNo,
          periodId,
          productIds: tempProductIds || []
        };
        this.getEditProducts();
        this.loadEditPeriodData();
      }
      this.dialogVisible = true;
    },
    addDialogData() {
      let submitData = { ...this.editForm };
      submitData.startChargeTime = moment(submitData.startChargeTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      if (submitData.productIds && submitData.productIds.length > 0) {
        submitData.productIds = submitData.productIds.join(",");
      }
      this.$showLoading();
      io.post(io.addChargeSetting, submitData, ret => {
        this.$hiddenLoading();
        if (ret.success) {
          this.dialogClose();
          this.search()
        }else{
          this.$alert(ret.desc)
        }
      }, ()=>{
         this.$hiddenLoading();
         this.$alert('网络错误')
      });
    },
    getEditProducts() {
      this.getProductData("getEdit").then(data => {
        this.editProducts = data;
      });
    },
    getProductData(type = "") {
      return new Promise((resolve, reject) => {
        io.post(
          io.apiAdminBaseProductListForAreaTeam,
          {
            areaTeamId:
              type === "getEdit"
                ? this.editForm.areaTeamId
                : this.query.areaTeamId
          },
          ret => {
            if (ret.success) {
              let productList = ret.data.map(function(item) {
                return { value: item.productId, text: item.name };
              });
              resolve(productList);
            } else {
              reject(ret);
            }
          }
        );
      });
    },
    loadEditPeriodData() {
      io.post(
        io.apiAdminPeriodListForAreaTeam,
        {
          areaTeamId: this.editForm.areaTeamId
        },
        ret => {
          if (ret.success) {
            this.editPeriods = ret.data;
          }
        }
      );
    },
    loadProductData: function() {
      if (!this.query.areaTeamId) {
        this.$alert("请选择区域！");
        return;
      }
      this.getProductData().then(
        data => {
          this.products = data;
        },
        ret => {
          this.$alert(ret.desc);
        }
      );
    },
    loadPeriodData(resolve) {
      io.post(
        io.apiAdminPeriodListForAreaTeam,
        {
          areaTeamId: this.query.areaTeamId
        },
        ret => {
          if (ret.success) {
            this.periods = ret.data;
          } else {
            this.$alert(ret.desc);
          }

          if (resolve) {
            resolve("success");
          }
        }
      );
    },
    search() {
      this.query.pageNo = 1;
      this.handleSearch();
    },
    handleSearch(pageNo) {
      let formData = this.getFormDate(pageNo);
      if (formData.areaTeamId != "") {
        this.$showLoading();
        io.post(
          io.chargeSettingPage,
          formData,
          ret => {
            this.$hiddenLoading();
            if (ret.success) {
              this.tableData = ret.data.list;
              this.total = ret.data.total;
            } else {
              this.$alert(ret.desc);
            }
          },
          () => {
            this.$hiddenLoading();
          }
        );
      } else {
        this.$alert("区域不能为空！");
      }
    },
    getFormDate(pageNo) {
      this.query.pageNo = pageNo || this.query.pageNo || 1;
      let formData = {};
      formData = { ...this.query };
      return formData;
    },
    handleExport() {
      let formData = this.getFormDate();
      io.downloadFile(io.exportAttendWarning, formData);
    }
  },
  computed: {
    areaTeams() {
      return this.$root.config.areaTeams || [];
    },
    busTeams() {
      let busTeams = this.query.areaTeamId
        ? this.$root.config.groupBusTeams[this.query.areaTeamId] || []
        : [];
      if (busTeams.length) {
        this.query.busTeamId = busTeams[0].busTeamId;
      }
      return busTeams;
    },
    grades: function() {
      return this.$root.config.grades || [];
    },
    subjects() {
      return [{ value: "", label: "全部科目" }].concat(
        this.$root.config.subjects.map(function(item) {
          return { value: item.subjectId, label: item.subjectName };
        })
      );
    }
  },
  created() {
    let promise = new Promise((resolve, reject) => {
      this.loadPeriodData(resolve);
    });
    this.loadProductData();
    promise.then(
      value => {
        // success
        this.handleSearch();
      },
      error => {
        // failure
      }
    );
  }
};
</script>
<style lang="less" scoped>
.chargeSegment {
  width: 120px;
}
.startChargeTime {
  width: 230px;
}
.lectureNoItem {
  float: left;
}
.lectureNoTxt {
  float: left;
  margin: 5px 15px 0 15px;
}
.lectureNoInput {
  width: 100px;
}
.showProductNames {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.productSelect {
  width: 80%;
}
</style>
